from datetime import datetime
import Webpage_script
import subprocess
import time
import json
import os
import random

app_name = "Toutiao"

def loop(tshark_path, initial_store_path):
    now = datetime.now()
    pcap_file_name = now.strftime("%Y-%m-%d_%H-%M-%S") + ".pcap"
    cmd = "{} -i 4 -F pcap -w {}\\{}".format(tshark_path, initial_store_path, pcap_file_name)
    tshark_pro = subprocess.Popen(cmd, shell=False)
    try:
        Webpage_script.run()
    except Exception as e:
        print(e)
    finally:
        tshark_pro.terminate()


if __name__ == '__main__':
    with open("./config.json", "r", encoding="utf-8") as fd:
        config = json.load(fd)
    tshark_path = config[app_name]["tshark_path"]
    initial_store_path = config[app_name]["initial_store_path"]
    if not os.path.exists(initial_store_path):
        os.mkdir(initial_store_path)
    loop_num = int(config[app_name]["loop_num"])
    for i in range(loop_num):
        loop(tshark_path, initial_store_path)
        # 一轮结束后的休息时间
        if i < loop_num - 1:
            time.sleep(30 * 60)
